/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package struts;

/**
 *
 * @author zhi
 */
import Service.*;
import java.io.BufferedReader;
import java.util.*;
import javabeans.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertyFilter;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


/**
 *
 * @author jo
 */
public class GroupPlanAction extends Action{

    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setHeader("Cache-Control", "no-store"); //HTTP1.1
        response.setHeader("Pragma", "no-cache"); //HTTP1.0
        response.setDateHeader("Expires", 0); //prevents catching at proxy server

        String action = request.getParameter("action");

        if("checkUpdate".equals(action)){
System.out.println("check update");

            //check the database
            boolean checkUpdate = true;
System.out.println("check udpate : " + checkUpdate);

            response.setContentType("text/json");
            if(checkUpdate == true) {
                response.getWriter().write("{ success: true, errors:{} }");
            }
            else {
                response.getWriter().write("{ success: false, errors:{info:'error'} }");
            }
        } else if("loadGroupPlan".equals(action)){
System.out.println("load group plan");
            int groupplanid = Integer.parseInt(request.getParameter("groupplanid"));
System.out.println(groupplanid);
            GroupPlanService gps = new GroupPlanServiceImpl();
            //check the database
            GroupPlan groupplan = gps.getGroupPlan(groupplanid);
            
            List<Event> groupPlanList = gps.getGroupEventList(groupplanid);
            groupplan.setEvents(groupPlanList);

            boolean loadGroupPlanSuccess = true;
            if(groupplan == null) {
                loadGroupPlanSuccess = false;
            }
System.out.println(loadGroupPlanSuccess);
System.err.println("events number: " + groupplan.getEvents().size());
            Map <String, Class> m = new HashMap <String, Class>();
            //m.put("eventInfos", EventInfo.class);
            JsonConfig config = new JsonConfig();
            config.setJsonPropertyFilter(new PropertyFilter(){
                public boolean apply(Object source, String name, Object value) {
                    if(name.equals("plan")||name.equals("groupplan")||name.equals("eventindex")||name.equals("password")||name.equals("gender")||name.equals("firstname")||name.equals("lastname")||name.equals("groups")||name.equals("personalplans")||name.equals("hibernateLazyInitializer"))
                    {
                        return true;
                    } else {
                        return false;
                    }
                }
            });
            JSONObject jsonObject = JSONObject.fromObject(groupplan, config);
System.out.println(jsonObject);

            response.setContentType("text/json");
            if(loadGroupPlanSuccess == true) {
                //String resp = "{'events':[{'color':'red','eventdate':'asdasd','eventdescript':'my event1','eventname':'event1','eventtime':'123','id':1001,'plan':null,'pointX':1.212,'pointY':121212.333,'type':'hotel'},{'color':'green','eventdate':'','eventdescript':'my event2','eventname':'event2','eventtime':'','id':1002,'plan':null,'pointX':0,'pointY':0,'type':null}],'plandescript':'my plan','planid':123,'planname':'plan1'}";
                String resp = jsonObject.toString();
                response.getWriter().write(resp);
            }
            else {
                response.getWriter().write("{ success: false, errors:{info:'error'} }");
            }
        } else if("saveGroupPlan".equals(action)) {
System.out.println("save group plan");
            StringBuffer stringBuffer = new StringBuffer();
            String line = null;
            try {
                BufferedReader reader = request.getReader();
                while ((line = reader.readLine()) != null)
                    stringBuffer.append(line);
            } catch (Exception e) { }//report an error }
System.out.println(stringBuffer);
            String str = stringBuffer.toString();
            //String str = "{\"planid\":42,\"planname\":\"asd\",\"plandescript\":\"asd\",\"eventInfos\":[{\"operation\":\"new\",\"event\":{\"id\":\"\",\"eventname\":\"1111\",\"type\":\"12\",\"pointX\":\"121\",\"pointY\":\"212\",\"eventdate\":\"12/01/2009\",\"eventtime\":\"3:15 AM\",\"color\":\"1212\",\"eventdescript\":\"1212\"}}]}";
            JSONObject jsonObject = JSONObject.fromObject(str);
            Map <String, Class> m = new HashMap <String, Class>();
            m.put("eventInfos", EventInfo.class);
            m.put("event", Event.class);
            m.put("members", Member.class);
            GroupPlanInfo groupplanInfo = (GroupPlanInfo) JSONObject.toBean(jsonObject, GroupPlanInfo.class, m);
            groupplanInfo.saveThisGroupPlan();
            //save to database
            boolean savePlanSuccess = true;

            response.setContentType("text/json");
            if(savePlanSuccess == true) {
                response.getWriter().write("{ success: true }");
            }
            else {
                response.getWriter().write("{ success: false, errors:{info:'error'} }");
            }
        } else if("deleteGroupPlan".equals(action)) {
System.out.println("delete group plan");
            int groupplanid = Integer.parseInt(request.getParameter("groupplanid"));
System.out.println(groupplanid);
            GroupPlanService gps = new GroupPlanServiceImpl();
            //boolean deletePlanSuccess = gps.deletePlan(groupplanid);
            
            boolean deletePlanSuccess = gps.deleteGroupPlan(gps.getGroupPlan(groupplanid));
            response.setContentType("text/json");
            if(deletePlanSuccess == true) {
                response.getWriter().write("{ success: true }");
            }
            else {
                response.getWriter().write("{ success: false, errors:{info:'error'} }");
            }

        }
       return super.execute(mapping, form, request, response);
    }

}
